package cn.zebra.dev.product.module.sku.service.impl;

import cn.zebra.dev.ibatis.plus.service.impl.ServiceImpl;
import cn.zebra.dev.product.module.sku.dao.ProductSkuAttributeDao;
import cn.zebra.dev.product.module.sku.entity.ProductSkuAttributeEntity;
import cn.zebra.dev.product.module.sku.service.ProductSkuAttributeService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.SneakyThrows;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.Future;

/**
 * @author runnable@sina.cn
 */
@Service
public class ProductSkuAttributeServiceImpl extends ServiceImpl<ProductSkuAttributeDao, ProductSkuAttributeEntity> implements ProductSkuAttributeService {

    /**
     * 批量线程保存
     *
     * @param entityList 商品分类集合
     * @return 成功返回true 保存失败返回false
     */
    @SneakyThrows
    @Override
    public boolean saveBatch(Collection<ProductSkuAttributeEntity> entityList) {
        if (entityList != null && entityList.size() > 0) {
            List<Future<Boolean>> list = new ArrayList<>(entityList.size());
            entityList.forEach(entity -> list.add(this.asyncSave(entity)));
            for (int i = list.size() - 1; i >= 0; i--) {
                if (!list.get(i).get()) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    /**
     * 异步保存
     *
     * @param entity 商品分类
     * @return 异步回调对象
     */
    @Override
    public Future<Boolean> asyncSave(ProductSkuAttributeEntity entity) {
        return AsyncResult.forValue(this.save(entity));
    }

    @Override
    public List<ProductSkuAttributeEntity> findListByProductId(Long productId) {
        return selectList("product_id = {0}", productId);
    }

    /**
     * 根据商品id和商品SKU Id 删除所有对应绑定属性
     *
     * @param productId 商品id
     * @param skuId     商品SKU Id
     * @return 成功返回 TRUE 失败返回FALSE
     */
    @Override
    public Boolean delete(Long productId, Long skuId) {
        return delete("product_id = {0} AND product_sku_id = {1}", productId, skuId);
    }

    /**
     * 根据商品sku Id查找所有商品sku属性集合
     *
     * @param productSkuId 商品sku Id
     * @return 商品sku属性集合
     */
    @Override
    public List<ProductSkuAttributeEntity> findListByProductSkuId(Long productSkuId) {
        return selectList("product_sku_id = {0}", productSkuId);
    }

    /**
     * 根据SkuId集合删除数据
     *
     * @param skuIds SkuId集合
     * @return 删除成功返回True 删除失败返回False
     */
    @Override
    public Boolean deleteByProductSkuIds(Collection<Long> skuIds) {
        UpdateWrapper<ProductSkuAttributeEntity> wrapper = new UpdateWrapper<>();
        wrapper.in("product_sku_id", skuIds);
        return remove(wrapper);
    }
}
